import { Grid, Input, InputNumber, Message, Radio, Select } from '@arco-design/web-react';
import { AxiosResponse } from 'axios';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ValidateRule, DictData } from '../../../types';
import DetailCard from '../../../components/detailCard';
import DetailItem from '../../../components/detailItem';
import { confirmDialog } from '../../../components/dialog';
import LoadingMask from '../../../components/loadingMask';
import { dictTag } from '../../../utils/utils';
import UploadImg from '../../../components/uploadImg';
import { dictDataOptions, getDict } from '../../../utils/utils';
import { clearRepeat, cloneDeep, flowKTOG, omitObject, validateField } from '../../../utils/utils';
import CardPackOrderDetailDialog from './cardPackOrderDetailDialog';
import {
  apiCardDetailWalletRefundApplyDetail,
  apiGetRefundInfoByCardId,
  apiPayAlipay,
  apicardDetailWalletRefundApplyEditAudit,
  apicardDetailWalletRefundApplyEditStatus,
  apicardDetailWalletRefundSysErrorUpdateReviceType,
} from './api';
import CardWalletLogDialog from './cardWalletLogDialog';
import PayCouponCardDialog from './payCouponCardDialog';
import RefundReasonList from './refundReasonList';
import { CardDetailWalletOrderInfo, CardDetailWalletRefundApply } from './types';
import DetailModal from '../../../components/detailModal';
const { Col, Row } = Grid;
interface Props {
  onCancel?: () => void;
  record: any,
  id: string | number,
  phone: string | number,
}
interface MenuTypes {
  menuId: string;
  // 菜单名称
  label: string;
  // 一级菜单图标
  icon?: any;
  // 唯一识别码
  key: string;
  // 点击后要跳转的链接
  link?: string;
  // 二级菜单列表 一级菜单上需要 二级上不需要
  subs?: MenuTypes[];
  // 父级菜单的key 任何一级都不用配 会自动赋值
  parent?: string;
  // 路由数组，不是为了跳转，只为匹配上任何一个后有个选中状态
  links?: string[];
  path: string;
  // parentPath?: string;
  component?: string;
  isDetail?: boolean;
  //----给历史记录使用的 从任何页面直接跳路由的页面 不会经历当前的menuChange和subMenuChange方法
  // 只会直接走Location/useEffect 就保存当前的地址和参数
  historyPath?: string;
  historyState?: any;
}
// 字段验证规则
const rule: ValidateRule = {
  applyPhone: { required: true, message: '手机号必填' },
  receiveType: { required: false, message: '备用方式必填' },
  receiveImg: { required: 'receiveType', receiveType: 'wx', message: '微信收款码必填' },
  receiveAccount: { required: 'receiveType', receiveType: 'alipay', message: '支付宝账号必填' },
  receiveName: { required: 'receiveType', receiveType: 'alipay', message: '支付宝姓名必填' },
  refundType: { required: true, message: '请退订本期和未生效套餐' },
  refundReason: { required: true, message: '退款原因必填' },
  refundAmount: { required: true, message: '退款金额必填，没有流水不能提交申请' },
  cleanBalance: { required: true, message: '是否清零必填' },
};
// 系统开关 状态
const CARD_SUPPLIER_PRODUCT_OPERATOR_TYPE = 'card_supplier_product_operator_type';
const CARD_DETAIL_WALLET_REFUND_APPLY_REFUND_TYPE = 'card_detail_wallet_refund_apply_refund_type';
const COMMON_YES_STATUS = 'common_yes_status';
const PAY_CONFIG_PAY_TYPE = 'pay_config_pay_type';
const COMMON_EFFECT_TYPE = 'common_effect_type';
const COMMON_PRETREATMENT_TYPE = 'common_pretreatment_type';
// 退款状态
const COMMON_REFUND_STATUS = 'common_refund_status';
// 付款类型
const CARD_DETAIL_WALLET_REFUND_APPLY_PAY_TYPE = 'card_detail_wallet_refund_apply_pay_type';

/** 供应商 流量卡 */
const JST_GOODS_NO = 'jst_goods_no';
/** 供应商 设备 */
const CARD_CONVERT_ORDER_EM_JST_GOODS_NO = 'card_convert_order_em_jst_goods_no';
/** 供应商 号卡 */
const CARD_CONVERT_ORDER_PHONE_JST_GOODS_NO = 'card_convert_order_phone_jst_goods_no';

export default function CardDetailWalletRefundApplyDetailPage({ onCancel, id, phone: applyPhone, record }: Props) {
  // 详情id 不论代表id的字段是什么，跳转的时候都用id
  // const { id } = useParams();
  // const { state } = useLocation();
  const { cardId } = record;
  const navigate = useNavigate();
  const [dictDatas, setDictDatas] = useState<Record<string, any>>({});
  useEffect(() => {
    async function fetchDictData() {
      const data = await getDict(CARD_SUPPLIER_PRODUCT_OPERATOR_TYPE,
        CARD_DETAIL_WALLET_REFUND_APPLY_REFUND_TYPE,
        CARD_DETAIL_WALLET_REFUND_APPLY_PAY_TYPE,
        PAY_CONFIG_PAY_TYPE,
        COMMON_EFFECT_TYPE,
        COMMON_PRETREATMENT_TYPE,
        COMMON_REFUND_STATUS,
        COMMON_YES_STATUS,
        JST_GOODS_NO,
        CARD_CONVERT_ORDER_EM_JST_GOODS_NO,
        CARD_CONVERT_ORDER_PHONE_JST_GOODS_NO);
      setDictDatas(data);
    }

    fetchDictData();
  }, []);

  const [cardDetailWalletOrderInfos, setCardDetailWalletOrderInfos] = useState<CardDetailWalletOrderInfo[]>(
    record?.cardDetailWalletOrderRefundList ?? []
  );
  // 每次编辑时修改的数据
  const [detailData, setDetailData] = useState<CardDetailWalletRefundApply | null | undefined>(
    record ?? {
      cleanBalance: 'N',
      applyPhone,
    }
  );
  // 是否可以原路退回 用于判断备用方式
  const [isSupportResourceReturn, setIsSupportResourceReturn] = useState(false);
  const [showRefundReasonList, setShowRefundReasonList] = useState(false);

  // 数据验证结果
  const [errorData, setErrorData] = useState<{ [x: string]: string }>({});
  // 订购记录弹框
  const [cardPackOrderDetailDialogShow, setCardPackOrderDetailDialogShow] = useState(false);
  // 充消记录
  const [cardWalletLog, setCardWalletLog] = useState(false);
  // 卡券明细弹框
  const [payCouponCard, setPayCouponCard] = useState(false);
  // 随机优惠总金额
  const [randomAmount, setRandomAmount] = useState<number | string>(0);
  // --------------------------------------------------------------------------------
  // 不能原路退且备用方式是支付宝的 支付宝打款步骤 {流水ID：1/2} 空=>未打款 1=>已打款 2=>打款失败
  const [alipayStep, setAlipayStep] = useState<{ [x: string]: string }>({});
  // 支付宝打款结果 {流水ID：'结果'}
  const [alipayRes, setAlipayRes] = useState<{ [x: string]: string }>({});
  // --------------------------------------------------------------------------------
  const [detail, setdetail] = useState<{ [x: string]: any }>({});
  useEffect(() => {
    getDetails()
  }, [id]);
  async function getDetails() {
    const res = await apiGetRefundInfoByCardId(id)
    setDetailData({
      ...detailData,
      ...res?.data?.data,
      applyPhone: applyPhone
    })
  }
  // 当前详情 根据id的值区分页面模式
  // const detail = useSelector((state: AppStore) =>
  //   id !== 'create' ? state.cardDetailWalletRefundApplyDetail?.[id ?? ''] : undefined
  // );

  useEffect(() => {
    if (!detailData?.id) {
      if (cardDetailWalletOrderInfos) {
        let temp = cardDetailWalletOrderInfos.some(
          (i) => (i.returnAmount ?? 0) > 0 && i.isSupportResourceReturn !== true
        );
        setIsSupportResourceReturn(!temp);
        if (temp && !detailData?.receiveType) {
          // 不能原路退
          handleChange('receiveType', 'alipay');
        }
      }
    }
  }, [cardDetailWalletOrderInfos]); //eslint-disable-line

  // 审核可选状态
  const arrOptions = [
    { value: 'pass', label: '通过' },
    { value: 'refuse', label: '未通过' },
  ];
  // 退款可选状态
  const listOptions = [
    { value: 'success', label: '同意' },
    { value: 'failure', label: '拒绝' },
  ];

  // 页面初次渲染时获取数据
  useEffect(() => {

    getRefundInfoByCardId();

  }, []); //eslint-disable-line

  // 页面详情数据获取到后存入编辑数据
  useEffect(() => {
    if (id !== 'create' && detail?.loaded && detail?.result) {
      let result = detail?.result;
      setCardDetailWalletOrderInfos(result.cardDetailWalletOrderRefundList ?? []);
      // 需要依赖详情数据加载别的数据的 在这里写
      let list = result.cardDetailWalletOrderRefundList ?? [];
      // 随机优惠总金额
      let randomAmount = 0;
      list.forEach((item: any) => {
        if (item.randomAmount) {
          randomAmount += Number(item.randomAmount);
        }
      });
      setRandomAmount(randomAmount.toFixed(2));
    }
  }, [detail]); //eslint-disable-line

  async function getRefundInfoByCardId() {
    try {
      let res = await apiGetRefundInfoByCardId(id);
      let data = res.data;
      if (data.code === 200) {
        let list = data.data.cardDetailWalletOrderRefundList ?? [];
        // 随机优惠总金额
        let randomAmount = 0;
        list.forEach((item: any) => {
          if (item.randomAmount) {
            randomAmount += Number(item.randomAmount);
          }
        });
        setRandomAmount(randomAmount.toFixed(2));
        let map: { [x: string]: CardDetailWalletOrderInfo } = {};
        if (record?.cardDetailWalletOrderRefundList) {
          record!.cardDetailWalletOrderRefundList.forEach((i: CardDetailWalletOrderInfo) => {
            let t = Object.assign(omitObject(i, ['delFlag', 'orderId', 'updateBy', 'createBy']), { id: i.orderId });
            map[t.id] = t;
          });
        }
        let useList: Array<CardDetailWalletOrderInfo> = [];
        list.forEach((i: CardDetailWalletOrderInfo) => {
          if (map[i.id!]) {
            useList.push(Object.assign({}, i, map[i.id!]));
          } else {
            useList.push(i);
          }
        });
        setCardDetailWalletOrderInfos(useList);
        setDetailData(Object.assign({}, data.data, detailData, applyPhone));
      } else {
        Message.warning(data.msg ?? '获取卡信息失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '获取卡信息失败');
    }
  }


  // 更新退款流水信息
  function updateRefundInfo(i: CardDetailWalletOrderInfo, key: string, value: any) {
    let _list: CardDetailWalletOrderInfo[] = [];
    for (let item of cardDetailWalletOrderInfos) {
      if (item.id !== i.id) {
        _list.push(item);
      } else {
        _list.push(Object.assign({}, i, { [key]: value }));
      }
    }
    setCardDetailWalletOrderInfos(_list);
    let _total = 0;
    _list.forEach((i) => {
      let amount = parseFloat(`${i.returnAmount ?? 0}`);
      _total += amount;
    });
    handleChange('refundAmount', _total);
  }

  // 任意字段修改时存入编辑数据
  function handleChange(key: string, value: any) {
    let data: any = cloneDeep(detailData);
    data[key] = value;
    if (key === 'pretreatmentType' && step === '1') {
      if (!!value) {
        data.effectType = 'success';
      } else {
        data.effectType = '';
      }
    }
    if (key === 'refundType' && data?.refundType === 'convertPhone' && step === '1') {
      data.pretreatmentType = 'refundSoldout';
      data.effectType = 'success';
    } else if (key === 'refundType' && data?.refundType !== 'convertPhone') {
      data.pretreatmentType = '';
      data.effectType = '';
      data.refundTypeImg = '';
    }
    setDetailData({ ...data, applyPhone });
  }
  /**
   * 系统异常 重新更换备用方式
   */
  async function handleSaveSysError() {
    let _rule: ValidateRule = {
      resourceBackup: { required: true, message: '打款方式不能为空' },
      receiveImg: { required: 'resourceBackup', resourceBackup: 'wx', message: '微信收款码必填' },
      receiveAccount: { required: 'resourceBackup', resourceBackup: 'alipay', message: '支付宝账号必填' },
      receiveName: { required: 'resourceBackup', resourceBackup: 'alipay', message: '支付宝姓名必填' },
    };
    let _data = {
      id: detailData?.id,
      resourceBackup: detailData?.resourceBackup,
      receiveImg: detailData?.receiveImg,
      receiveAccount: detailData?.receiveAccount,
      receiveName: detailData?.receiveName,
    };
    let validateRes = validateField(_data, _rule);
    setErrorData(validateRes);
    if (Object.keys(validateRes).length) return;
    LoadingMask.show('正在保存...');
    try {
      let res = await apicardDetailWalletRefundSysErrorUpdateReviceType(_data);
      let data = res.data;
      if (data.code === 200) {
        Message.success({ id: 'save', content: '保存成功' });

        // navigate(-1);
      }
    } catch (e: any) {
      Message.error({ id: 'save', content: e.message ?? '保存失败' });
    } finally {
      LoadingMask.hide();
    }
  }

  // 保存
  async function handleSave(type: string) {
    let _rule = { ...rule };
    _rule.receiveType = { required: !isSupportResourceReturn, message: '备用方式不能为空' };

    let validateRes = validateField(detailData, _rule);
    if (validateRes.refundReason) {
      Message.warning(validateRes.refundReason);
    }
    setErrorData(validateRes);
    if (!detailData?.refundAmount) {
      return Message.warning('退款金额必填，没有流水不能提交申请')
    }
    console.log(validateRes, 'validateRes')
    if (Object.keys(validateRes).length) return;

    let _infos: Array<CardDetailWalletOrderInfo> = [];
    if (step === '1') {
      // if (detailData?.refundType === 'convertPhone' && !detailData?.refundTypeImg) {
      //   Message.warning('号卡充值凭证必填');
      //   return;
      // }
      for (let i of cardDetailWalletOrderInfos) {
        if ((i.returnAmount && !i.refundImg) || (i.refundImg && !i.returnAmount)) {
          Message.warning('需要退款的交易流水必须上传退款凭证和填写申退金额');
          return;
        } else if (i.returnAmount && i.refundImg) {
          _infos.push(i);
        }
      }
      if (!_infos.length) {
        Message.warning('没有上传要退款的交易流水退款凭证和申退金额');
        return;
      }
    } else {
      _infos = detailData!.cardDetailWalletOrderRefundList;
    }

    let typeStr = '';
    let _data = Object.assign({}, detailData, { cardDetailWalletOrderRefundList: _infos });
    if (type === 'add') {
      typeStr = '提交';
      _data.status = 'wait';
    } else if (type === 'editAudit') {
      typeStr = '审核';
      let _list = arrOptions.map((i) => i.value);
      if (!_list.includes(_data.status ?? '')) {
        Message.warning('请选择审核状态');
        return;
      }
    } else if (type === 'editStatus') {
      _data.cardDetailWalletRefundApplyReturnSourceBoList = cardDetailWalletOrderInfos
        .filter((i) => !!i.isSourceRefund)
        .map((i) => ({
          cardDetailWalletOrderRefundId: i.id,
          sourceAmount: i.sourceRefundAmount ?? parseFloat((i.returnAmount ?? '0').toString()),
        }));

      typeStr = '退款';
      let _list = listOptions.map((i) => i.value);
      if (!_list.includes(_data.status ?? '')) {
        Message.warning('请选择退款状态');
        return;
      }
      // if (!_data.payType) {
      //   Message.warning('请选择退款方式');
      //   return;
      // }
    } else {
      Message.warning('状态错误');
      return;
    }
    LoadingMask.show(`正在${typeStr}...`);

    let res: AxiosResponse | undefined;

    try {
      if (type === 'add') {
        // 提交审核申请
        res = await apiCardDetailWalletRefundApplyDetail(_data);
      } else if (type === 'editAudit') {
        // 待审核
        res = await apicardDetailWalletRefundApplyEditAudit(_data);
      } else if (type === 'editStatus') {
        // 待退款
        res = await apicardDetailWalletRefundApplyEditStatus(_data);
      } else {
        Message.warning('状态错误');
      }
      let data = res?.data;
      if (data.code === 200) {
        Message.success({ id: 'save', content: `${typeStr}成功` });
        // dispatch(
        //   cardDetailWalletRefundApplyListRequest({
        //     pageSize: main.defaultPageSize,
        //     pageNum: 1,
        //     params: main.currPageState['cardDetailWalletRefundApply'],
        //     forceRefresh: true,
        //   })
        // );
        handleConfirm()
        // navigate(-1);
      } else {
        Message.warning({ id: 'save', content: data.msg ?? `${type}失败` });
      }
    } catch (e: any) {
      Message.error({ id: 'save', content: e.message ?? `${type}失败` });
    } finally {
      LoadingMask.hide();
    }
  }
  function handleConfirm() {
    if (onCancel) {
      onCancel();
    }
  }
  //----------------额外操作 / 数据-------------------
  // 支付宝打款
  async function handleAlipay(i: CardDetailWalletOrderInfo) {
    let pwd = '';
    let modalRes = await confirmDialog({
      title: '支付宝打款',
      content: (
        <div className="bw-100">
          <DetailItem label="打款账号" labelSpan={4} outlet={4}>
            {detailData?.receiveAccount}
          </DetailItem>
          <DetailItem label="打款金额" labelSpan={4} outlet={4}>
            {i.sourceRefundAmount ?? i.returnAmount}
          </DetailItem>
          <DetailItem label="支付密码" labelSpan={4} outlet={4}>
            <Input
              placeholder="请输入支付密码"
              onChange={(v) => {
                pwd = v;
              }}
            />
          </DetailItem>
        </div>
      ),
      okText: '确认打款',
    });
    if (!modalRes) return;
    if (!pwd) return Message.warning('请输入支付密码');

    try {
      LoadingMask.show('正在打款...');
      let res = await apiPayAlipay(i.id!, i.sourceRefundAmount ?? i.returnAmount!, pwd);
      let data = res.data;
      if (data.code === 200) {
        Message.success({ id: 'save', content: data.msg || '打款成功' });
        setAlipayStep({ ...alipayStep, [i.id!]: '1' });
        setAlipayRes({ ...alipayRes, [i.id!]: data.msg || '打款成功' });
      } else {
        Message.warning({ id: 'save', content: data.msg ?? '打款失败' });
        setAlipayStep({ ...alipayStep, [i.id!]: '2' });
        setAlipayRes({ ...alipayRes, [i.id!]: data.msg || '打款失败' });
      }
    } catch (e: any) {
      Message.error({ id: 'save', content: e.message ?? '打款失败' });
      setAlipayStep({ ...alipayStep, [i.id!]: '2' });
      setAlipayRes({ ...alipayRes, [i.id!]: e.message || '打款失败' });
    } finally {
      LoadingMask.hide();
    }
  }

  //-------------------------------------------------
  let oldStatus = detail?.result?.status;
  let step =
    oldStatus === 'failure' || oldStatus === 'success' || oldStatus === 'refuse' || oldStatus === 'sysError'
      ? '4'
      : oldStatus === 'pass'
        ? '3'
        : oldStatus === 'wait'
          ? '2'
          : '1';
  // let stepStr =
  //   step === '1'
  //     ? '提交信息'
  //     : step === '2'
  //     ? '审核退款'
  //     : step === '3'
  //     ? '退款'
  //     : dictDatas[COMMON_REFUND_STATUS].find((i) => i.dictValue === detailData?.status)?.dictLabel || '完成';
  // 不能原路退的原因
  let resourceReturnReason: string[] = [];
  cardDetailWalletOrderInfos.forEach((i) => {
    if ((i.returnAmount ?? 0) > 0) {
      resourceReturnReason = resourceReturnReason.concat(i.resourceReturnReason ?? []);
    }
  });
  resourceReturnReason = clearRepeat(resourceReturnReason) as string[];
  return (
    <DetailModal
      className="bw-90"
      contentClassName="h-500"
      show
      title="退款申请"
      onCancel={onCancel}
      onConfirm={() => handleSave('add')}
      footChildrenLeft={<a href='#' style={{ float: 'left' }} onClick={(e: any) => {
        e.preventDefault(); // 阻止默认行为
        setShowRefundReasonList(true)
      }}>退款原因</a>}
      confirmText="确定"
    >
      <div className="bh-100 detail-page overflow-y card-detail-wallet-refund-apply-detail-page">

        <div className="  scroll-bar-h-min page-white border-radius-8">
          <div className="flex-1">
            <DetailCard title="卡片信息">
              <DetailItem label="充值卡号" outlet={2} labelSpan={8}>{detailData?.iccid}</DetailItem>
              <DetailItem label="旧卡号" outlet={2} labelSpan={8}>{detailData?.oldIccid}</DetailItem>
              <DetailItem label="*运营商" outlet={2} labelSpan={8}>
                {dictTag(detailData?.operatorType, dictDatas[CARD_SUPPLIER_PRODUCT_OPERATOR_TYPE])}
              </DetailItem>
              <DetailItem label="手机号" outlet={2} labelSpan={8}>{applyPhone}</DetailItem>
              <DetailItem label="余额" outlet={2} labelSpan={8}>
                {detailData?.availableAmount}
                <span
                  className="h-32 field-line-height text-primary-color font-12 ml-5 cursor-pointer"
                  onClick={() => setCardWalletLog(true)}
                >
                  充消记录
                </span>
              </DetailItem>
              <DetailItem label="已用流量" outlet={2} labelSpan={8}>
                <span>{flowKTOG(detailData?.usedFlow).toFixed(2)}G</span>
                <span
                  className="h-32 field-line-height text-primary-color font-12 ml-5 cursor-pointer"
                  onClick={() => setCardPackOrderDetailDialogShow(true)}
                >
                  订购记录
                </span>
              </DetailItem>
              <DetailItem label="活动金额" outlet={2} labelSpan={8}>
                <span>{detailData?.premiseAmount}</span>
                <span
                  className="h-32 field-line-height text-primary-color font-12 ml-5 cursor-pointer"
                  onClick={() => setPayCouponCard(true)}
                >
                  卡券明细
                </span>
              </DetailItem>
              <DetailItem label="随机优惠总额" outlet={4} labelSpan={6}>{randomAmount.toString()}</DetailItem>
            </DetailCard>
            <DetailCard title="申请信息" className='mt-10'>
              <DetailItem label="退款类型" outlet={4} labelSpan={6} error={errorData?.refundType}>
                <Select
                  disabled={step !== '1'}
                  className="m-select"
                  options={dictDataOptions(dictDatas[CARD_DETAIL_WALLET_REFUND_APPLY_REFUND_TYPE])}
                  value={detailData?.refundType}
                  onChange={(v) => handleChange('refundType', v)}
                />
              </DetailItem>
              {step === '1' && (
                <>
                  <DetailItem label="预处理方式" outlet={4} labelSpan={6}>
                    <Select
                      allowClear
                      className="m-select"
                      disabled={detailData?.refundType === 'convertPhone' && step === '1'}
                      options={dictDataOptions(dictDatas[COMMON_PRETREATMENT_TYPE])}
                      value={detailData?.pretreatmentType}
                      onChange={(v) => handleChange('pretreatmentType', v)}
                    />
                  </DetailItem>

                  <DetailItem label="生效类型" outlet={4} labelSpan={6} required={!!detailData?.pretreatmentType} error={errorData?.effectType}>
                    <Select
                      allowClear
                      className="m-select"
                      // disabled
                      options={dictDataOptions(dictDatas[COMMON_EFFECT_TYPE])}
                      value={detailData?.effectType}
                      onChange={(v) => handleChange('effectType', v)}
                    />
                  </DetailItem>
                  <Col span={12} />
                </>
              )}
              <DetailItem label="备用方式" outlet={4} labelSpan={6} required={!isSupportResourceReturn} error={errorData?.receiveType}>
                <Select
                  allowClear
                  className="m-select"
                  disabled={step !== '1'}
                  options={[
                    { label: '微信', value: 'wx' },
                    { label: '支付宝', value: 'alipay' },
                    { label: '原路退', value: 'source' },
                  ]}
                  value={detailData?.receiveType}
                  onChange={(v) => handleChange('receiveType', v)}
                />
              </DetailItem>
              <Col span={18} className="pl-20 text-red-color" >
                {resourceReturnReason.map((i, idx) => (
                  <div className="font-12" key={i + idx}>
                    {i}
                  </div>
                ))}
              </Col>

              {detailData?.receiveType === 'wx' && (
                <DetailItem label="微信收款码" outlet={4} labelSpan={6} error={errorData?.receiveImg}>
                  <UploadImg
                    width={80}
                    disabled={step !== '1'}
                    values={detailData?.receiveImg ? [detailData?.receiveImg] : []}
                    onlyReturnUrl
                    onChange={(v) => {
                      handleChange('receiveImg', v?.length ? v[0] : '');
                    }}
                  />
                </DetailItem>
              )}
              {detailData?.receiveType === 'alipay' && (
                <DetailItem label="支付宝姓名" outlet={4} labelSpan={6} error={errorData?.receiveName}>
                  <Input
                    disabled={step !== '1'}
                    value={detailData?.receiveName}
                    className="m-input"
                    onChange={(v) => handleChange('receiveName', v)}
                  />
                </DetailItem>
              )}
              {detailData?.receiveType === 'alipay' && (
                <DetailItem label="支付宝账号" outlet={4} labelSpan={6} error={errorData?.receiveAccount}>
                  <Input
                    disabled={step !== '1'}
                    value={detailData?.receiveAccount}
                    className="m-input"
                    onChange={(v) => handleChange('receiveAccount', v)}
                  />
                </DetailItem>
              )}


              <Col span={24}>
                <div className="h-32 d-flex-r ai-center text-second-color font-12 ml-5" style={{ float: 'right' }}>
                  *选择退全款请先退订本期和未生效套餐
                </div>
              </Col>

              <DetailItem label="是否清零余额" outlet={4} labelSpan={6} error={errorData?.cleanBalance}>
                <div className="radio-box">
                  <Radio.Group
                    disabled={step !== '1'}
                    options={dictDataOptions(dictDatas[COMMON_YES_STATUS])}
                    value={detailData?.cleanBalance}
                    onChange={(v) => handleChange('cleanBalance', v)}
                  />
                </div>
              </DetailItem>
              {detailData?.refundType === 'convertPhone' && (
                <DetailItem
                  // required={detailData?.refundType === 'convertPhone'}
                  label="号卡充值凭证"
                  outlet={4} labelSpan={6}
                  error={errorData?.refundTypeImg}
                >
                  <UploadImg
                    width={80}
                    limit={3}
                    disabled={step !== '1'}
                    onlyReturnUrl
                    values={detailData?.refundTypeImg ? detailData?.refundTypeImg.split(';') : []}
                    onChange={(v) => handleChange('refundTypeImg', v.join(';'))}
                  />
                </DetailItem>
              )}
              <DetailItem label="申请备注" outlet={4} labelSpan={6} error={errorData?.applyRemark}>
                <Input.TextArea
                  className="m-input"
                  maxLength={200}
                  showWordLimit
                  disabled={step !== '1'}
                  value={detailData?.applyRemark}
                  autoSize={{ minRows: 2 }}
                  onChange={(v) => handleChange('applyRemark', v)}
                />
              </DetailItem>
            </DetailCard>
            {detailData?.refundType === 'convertPhone' && detailData?.cardDetailConvertOrder?.id && (
              <DetailCard title="换卡信息">
                <DetailItem label="目标卡号">{detailData?.cardDetailConvertOrder?.businessNo}</DetailItem>
                <DetailItem label="供应商">
                  {detailData?.cardDetailConvertOrder?.jstGoodsNo
                    ? dictTag(
                      detailData?.cardDetailConvertOrder?.jstGoodsNo,
                      dictDatas[
                      detailData?.cardDetailConvertOrder?.convertType === 'flow'
                        ? JST_GOODS_NO
                        : detailData?.cardDetailConvertOrder?.convertType === 'em'
                          ? CARD_CONVERT_ORDER_EM_JST_GOODS_NO
                          : CARD_CONVERT_ORDER_PHONE_JST_GOODS_NO
                      ]
                    )
                    : '--'}
                </DetailItem>
                <DetailItem label="状态">{detailData?.cardDetailConvertOrder.businessStatus}</DetailItem>
                <DetailItem label="目标资费">
                  {detailData?.cardDetailConvertOrder?.businessJson?.cardProductName}
                </DetailItem>
                <DetailItem label="余额">{detailData?.availableAmount}</DetailItem>
                <DetailItem label="补贴金额">{detailData?.cardDetailConvertOrder?.bonusAmount}</DetailItem>
                <DetailItem label={<span className="text-red-color">合计需退金额</span>}>
                  <span className="text-red-color">
                    {Number(detailData?.availableAmount ?? 0) +
                      Number(detailData?.cardDetailConvertOrder?.bonusAmount ?? 0)}
                  </span>
                </DetailItem>
                <DetailItem label="凭证" outlet={4}>
                  <UploadImg disabled values={detailData?.cardDetailConvertOrder?.proofUrl?.split(';')} />
                </DetailItem>
                {!!detailData?.cardDetailConvertOrder?.receiptImg && (
                  <DetailItem label="微信收款码">
                    <UploadImg disabled values={[detailData?.cardDetailConvertOrder?.receiptImg]} />
                  </DetailItem>
                )}
                {!!detailData?.cardDetailConvertOrder?.receiptAccount && (
                  <DetailItem label="支付宝账号">{detailData?.cardDetailConvertOrder?.receiptAccount}</DetailItem>
                )}
                {!!detailData?.cardDetailConvertOrder?.receiptName && (
                  <DetailItem label="支付宝账号">{detailData?.cardDetailConvertOrder?.receiptName}</DetailItem>
                )}
              </DetailCard>
            )}





            <DetailCard title="交易流水">
              <div className="d-flex-r ai-center jc-end bw-100 text-second-color">
                <div>实际退款金额</div>
                <div className="text-red-color ml-10">{errorData?.refundAmount}</div>
                <div className="text-primary-color ml-10">{detailData?.refundAmount}</div>
                <div className="font-12 ml-10">*退款预计3-5天到账</div>
              </div>

              {cardDetailWalletOrderInfos.length ? (
                cardDetailWalletOrderInfos.map((i) => (
                  <Row className="bw-100" key={i.id}>
                    <Col span={24}>
                      <div className="d-flex-r bw-100 jc-between font-12 ai-center mb-10 p-5 page-bg border-radius-4">
                        <div className="mr-10 bw-50">
                          <div>
                            商户号：{i.payConfigDetailMchId}
                            {i.id === 'default' ? '无' : ''}
                          </div>
                          <div
                            className={
                              (i.resourceReturnReason ?? []).some((i) => i.includes('不支持')) ? 'text-error-color' : ''
                            }
                          >
                            商户名称： {i.payConfigDetailMchName}
                          </div>
                          <div
                            className={
                              (i.resourceReturnReason ?? []).some((i) => i.includes('未对接')) ? 'text-error-color' : ''
                            }
                          >
                            交易类型：
                            {
                              dictDatas?.[PAY_CONFIG_PAY_TYPE]?.find((j: DictData) => j.dictValue === i.payType)
                                ?.dictLabel
                            }
                          </div>
                          <div>商户类型：{i.payConfigName}</div>
                          <div>交易流水：{i.transactionId}</div>
                          <div>商户单号：{i.orderSn}</div>
                          <div className={dayjs().diff(dayjs(i.createTime), 'month') >= 11 ? 'text-error-color' : ''}>
                            支付时间：{i.createTime}
                          </div>
                          <div>充值金额：{i.payAmount}</div>
                          <div>到账金额：{i.amount}</div>
                        </div>

                        <div className="mr-10">
                          <div>
                            本次实际退款：
                            {(
                              (parseFloat(i.amount ?? '0') / parseFloat(i.payAmount ?? '0')) *
                              (i.returnAmount ?? 0)
                            ).toFixed(2)}
                          </div>
                          <div>已退金额：{i.refundAmount ?? 0}</div>
                        </div>

                        <div>
                          <div className="d-flex-r ai-center">
                            <div>支付凭证:</div>
                            <div className="w-100">
                              <UploadImg
                                title="上传退款凭证"
                                width={60}
                                limit={2}
                                disabled={step !== '1'}
                                values={i.refundImg ? i.refundImg.split(';') : []}
                                onlyReturnUrl
                                onChange={(v) => updateRefundInfo(i, 'refundImg', v.join(';'))}
                              />
                            </div>
                          </div>
                          {(i.returnAmount ?? 0) > 0 && !i.refundImg && (
                            <div className="font-size-12 text-red-color">申退金额大于0支付凭证必输</div>
                          )}
                        </div>

                        {step === '1' ? (
                          <InputNumber
                            className="m-input w-100 ml-20"
                            placeholder="申退金额"
                            min={0}
                            value={
                              parseFloat((i.returnAmount ?? '0').toString()) === 0
                                ? undefined
                                : parseFloat((i.returnAmount ?? '0').toString())
                            }
                            onChange={(v) => updateRefundInfo(i, 'returnAmount', v)}
                          />
                        ) : (
                          <div className="mr-10">申退金额：{i.returnAmount}</div>
                        )}
                      </div>
                      <div className="font-12 text-error-color">
                        {!!i.resourceReturnReason?.length && `不能原路退原因:${i.resourceReturnReason!.join('/')}`}
                      </div>
                      {(!!i.isExistSuccessInvoice || !!i.isExistWaitInvoice) && (
                        <div className="font-12 text-gold-color">
                          退款影响：
                          {!!i.isExistWaitInvoice && '存在处理中的发票申请，可能导致开票金额减少或开票申请失效'}
                          {!!i.isExistSuccessInvoice && !!i.isExistWaitInvoice && '/'}
                          {!!i.isExistSuccessInvoice && '退款成功会导致原有发票失效'}
                        </div>
                      )}
                    </Col>

                  </Row>
                ))
              ) : (
                <div>暂无交易流水</div>
              )}
            </DetailCard>

            {/* 订购记录 */}
            {!!cardPackOrderDetailDialogShow && (
              <CardPackOrderDetailDialog
                cardId={cardId !== undefined ? cardId : detailData?.cardId}
                onCancel={() => setCardPackOrderDetailDialogShow(false)}
              />
            )}
            {/* 充销记录 */}
            {cardWalletLog && (
              <CardWalletLogDialog
                iccid={detailData?.iccid}
                cardWalletLog={cardWalletLog}
                onCancel={() => setCardWalletLog(false)}
              />
            )}
            {/* 卡券明细 */}
            {payCouponCard && (
              <PayCouponCardDialog
                iccid={detailData?.iccid}
                payCouponCard={payCouponCard}
                onCancel={() => setPayCouponCard(false)}
              />
            )}
          </div>
          {
            showRefundReasonList && <RefundReasonList
              valueInfos={detailData?.refundReason}
              disabled={step !== '1'}
              reasonType="wallet"
              onChange={(v: any) => handleChange('refundReason', v)}
              onConfirm={(e) => {
                handleChange('refundReason', e)
                setShowRefundReasonList(false)
              }}
              onCancel={() => {
                setShowRefundReasonList(false)
              }}
            />
          }

        </div>
      </div>
    </DetailModal>

  );
}
